#include "TextWindowIterator.h"
#include <stdio.h>
#include <string.h>

TextWindowIterator::TextWindowIterator(FILE *file, int win_length)
{
	this->file = file;
	this->win_length = win_length;

	if(this->file == NULL && win_length == 0) {
		this->eof = true;
		this->buf = NULL;
	} else {
		this->buf = new TextWindow(win_length);

		// Initialize the buffer with the first win_length characters from
		// the input stream.
		int n = fread(this->buf->substring, sizeof(char), win_length, this->file);
		this->buf->length = n;
		this->buf->file_position = 0;
		this->eof = feof(this->file);
	}
}

TextWindowIterator::~TextWindowIterator(void)
{
	if(this->buf) {
		delete this->buf;
		this->buf = NULL;
	}
}

TextWindow &TextWindowIterator::operator*() {
	return *(this->buf);
}

TextWindowIterator &TextWindowIterator::operator++() {
	memcpy(this->buf->substring, this->buf->substring+1, this->win_length-1);
	fread(this->buf->substring+win_length-1, sizeof(char), 1, this->file);
	this->eof = feof(this->file);
	this->buf->file_position ++;
	return *this;
}

bool TextWindowIterator::operator==(const TextWindowIterator &other) {
	return (this->eof == other.eof);
}

bool TextWindowIterator::operator!=(const TextWindowIterator &other) {
	return !(*this == other);
}

TextWindowIterator TextWindowIterator::end() {
	return TextWindowIterator(NULL, 0);
}